package com.cn.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.cn.bean.CancelOrder;
import com.cn.bean.EnumOrder;
import com.cn.bean.Order;
import com.cn.bean.Provider;
import com.cn.bean.Resident;
import com.cn.bean.SecondKill;
import com.cn.bean.Servicecatalog;
import com.cn.bean.Servicetype;
import com.cn.dao.CancelOrderDAO;
import com.cn.dao.OrderDAO;
import com.cn.dao.ProviderDAO;
import com.cn.dao.ResidentDAO;
import com.cn.dao.SecondKillDAO;
import com.cn.dao.ServicecatalogDAO;
import com.cn.dao.ServicetypeDAO;
import com.cn.entity.OrderDetail2;
import com.cn.entity.TotalOrder;
import com.cn.service.OrderService;

public class OrderServiceImpl implements OrderService {
	private OrderDAO orderDao = null;
	private ProviderDAO providerDao = null;
	private ResidentDAO residentDao = null;
	private ServicecatalogDAO servicecatalogDao = null;
	private ServicetypeDAO servicetypeDao = null;
	private CancelOrderDAO cancelorderDao = null;
	private SecondKillDAO secondkillDao = null;
	HttpServletRequest request;

	public SecondKillDAO getSecondkillDao() {
		return secondkillDao;
	}

	public void setSecondkillDao(SecondKillDAO secondkillDao) {
		this.secondkillDao = secondkillDao;
	}

	public CancelOrderDAO getCancelorderDao() {
		return cancelorderDao;
	}

	public void setCancelorderDao(CancelOrderDAO cancelorderDao) {
		this.cancelorderDao = cancelorderDao;
	}

	public ResidentDAO getResidentDao() {
		return residentDao;
	}

	public void setResidentDao(ResidentDAO residentDao) {
		this.residentDao = residentDao;
	}

	public OrderDAO getOrderDao() {
		return orderDao;
	}

	public void setOrderDao(OrderDAO orderDao) {
		this.orderDao = orderDao;
	}

	public ProviderDAO getProviderDao() {
		return providerDao;
	}

	public void setProviderDao(ProviderDAO providerDao) {
		this.providerDao = providerDao;
	}

	public ServicecatalogDAO getServicecatalogDao() {
		return servicecatalogDao;
	}

	public void setServicecatalogDao(ServicecatalogDAO servicecatalogDao) {
		this.servicecatalogDao = servicecatalogDao;
	}

	public ServicetypeDAO getServicetypeDao() {
		return servicetypeDao;
	}

	public void setServicetypeDao(ServicetypeDAO servicetypeDao) {
		this.servicetypeDao = servicetypeDao;
	}

	/**
	 * 下单并返回下单结果
	 */
	public String placeOrder() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		int re_id = Integer.parseInt(request.getParameter("re_id"));	//从安卓端提交的数据中得到居民id
		int pro_id = Integer.parseInt(request.getParameter("pro_id"));	//从安卓端提交的数据中得到供应商id
		int sc_id = Integer.parseInt(request.getParameter("sc_id"));	//从安卓端提交的数据中得到服务种类id
		Resident re = new Resident();
		re.setId(re_id);
		Provider p = new Provider();
		p.setId(pro_id);
		Servicecatalog sc = new Servicecatalog();
		sc.setId(sc_id);
		String address = request.getParameter("address");				//从安卓端提交的数据中得到服务地址
		String time = request.getParameter("time");						//从安卓端提交的数据中得到服务时间
		System.out.println(time);
		String message = request.getParameter("message");				//如果居民没有填写留言则置为空
		if (message.equals("请输入服务留言")) {
			message = "";
		}
		float price = Float.parseFloat(request.getParameter("price"));	//从安卓端提交的数据中得到订单价格
		Order order = new Order();
		order.setResident(re);
		order.setProvider(p);
		order.setServicecatalog(sc);
		order.setAddress(address);
		order.setMessage(message);
		order.setPrice(price);											//设置订单的信息
		order.setState(EnumOrder.ORDER_WAIT_TAKE);						//将订单的状态设置为待接单
		order.setTime(new Date());										//设置下单时间，为当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = sdf.parse(time);	
		order.setService_time(date);									//将服务时间转化为Date并设置进订单
		if (orderDao.save(order)) {										//讲订单保存到数据库里
			System.out.println(order.getId());
			CancelOrder cancelOrder = new CancelOrder();
			cancelOrder.setOrder_id(order.getId());
			cancelOrder.setPlacetime(order.getTime());
			cancelorderDao.save(cancelOrder);							//同时将订单复制一份到待取消订单中
			return "succeed";
		} else {
			return "failed";
		}

	}

	/**
	 * 秒杀活动
	 * 
	 * @return
	 * @throws Exception
	 */
	public synchronized String placeSecondKillOrder() throws Exception {

		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		int id = Integer.parseInt(request.getParameter("id"));
		int re_id = Integer.parseInt(request.getParameter("re_id"));
		
		// 同步访问数据库中秒杀的数量
			SecondKill sk = (SecondKill) secondkillDao.findById(id);
			if (sk == null) {						//若秒杀活动已经结束则返回失败
				System.out.println("失败的是"+re_id);
				return "failed";
			} else {
				int num = sk.getNum();
				num--;
				if (num == 0) {// 如果为最后一个抢到的，就删除这个活动
					secondkillDao.delete(sk);
				} else {
					sk.setNum(num);
					secondkillDao.update(sk);
				}
			}

			
			int pro_id = Integer.parseInt(request.getParameter("pro_id"));	//从安卓端返回的数据中得到供应商id
			int sc_id = Integer.parseInt(request.getParameter("sc_id"));	//从安卓端返回的数据中得到服务种类id
			Resident re = new Resident();
			re.setId(re_id);
			Provider p = new Provider();
			p.setId(pro_id);
			Servicecatalog sc = new Servicecatalog();
			sc.setId(sc_id);
			String address = request.getParameter("address");
			String time = request.getParameter("time");
			String message = request.getParameter("message");
			if (message.equals("请输入服务留言")) {
				message = "";
			}
			float price = Float.parseFloat(request.getParameter("price"));
			Order order = new Order();
			order.setResident(re);
			order.setProvider(p);
			order.setServicecatalog(sc);
			order.setAddress(address);
			order.setMessage(message);
			order.setPrice(price);
			order.setState(EnumOrder.ORDER_WAIT_COMFIRM);				//将订单状态设置为待确认
			order.setTime(new Date());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = sdf.parse(time);
			order.setService_time(date);
			if (orderDao.save(order)) {									//将成功秒杀的订单存入数据库中
				System.out.println("成功的是"+re_id);
				return "succeed";
			} else {
				return "fail";
			}
		}
	

	/**
	 * 获得该用户未接单订单
	 * 
	 * @return 订单list
	 * @throws Exception
	 */
	public List getWaitTakeOrder() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		String re_account = request.getParameter("re_account");
		Resident r = (Resident) residentDao.findByAccount(re_account);
		int re_id = r.getId();
		List list = orderDao.getWaitTakeOrder(re_id);
		List orderList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			TotalOrder to = new TotalOrder();
			Order order = (Order) list.get(i);
			to.setId(order.getId());
			Provider p = (Provider) providerDao.findById(order.getProvider().getId());
			to.setPro_name(p.getName());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			to.setTime(sdf.format(order.getTime()));
			Servicecatalog sc = (Servicecatalog) servicecatalogDao.findById(order.getServicecatalog().getId());
			Servicetype st = (Servicetype) servicetypeDao.findById(sc.getServicetype().getId());
			to.setSt_sc_name(st.getName() + "-" + sc.getName());
			to.setState("未接单");
			orderList.add(to);
		}
		return orderList;
	}

	/**
	 * 获得该用户待确认订单
	 * 
	 * @return 订单list
	 * @throws Exception
	 */
	public List getWaitConfirmOrder() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		String re_account = request.getParameter("re_account");
		Resident r = (Resident) residentDao.findByAccount(re_account);
		int re_id = r.getId();
		List list = orderDao.getWaitConfirmOrder(re_id);
		List orderList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			TotalOrder to = new TotalOrder();
			Order order = (Order) list.get(i);
			to.setId(order.getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			to.setTime(sdf.format(order.getTime()));
			Provider p = (Provider) providerDao.findById(order.getProvider().getId());
			to.setPro_name(p.getName());
			Servicecatalog sc = (Servicecatalog) servicecatalogDao.findById(order.getServicecatalog().getId());
			Servicetype st = (Servicetype) servicetypeDao.findById(sc.getServicetype().getId());
			to.setSt_sc_name(st.getName() + "-" + sc.getName());
			to.setState("待确认");
			orderList.add(to);
		}
		return orderList;
	}

	/**
	 * 获得该用户待评价订单
	 * 
	 * @return 订单list
	 * @throws Exception
	 */
	public List getWaitRemarkOrder() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		String re_account = request.getParameter("re_account");
		Resident r = (Resident) residentDao.findByAccount(re_account);
		int re_id = r.getId();
		List list = orderDao.getWaitRemarkOrder(re_id);
		List orderList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			TotalOrder to = new TotalOrder();
			Order order = (Order) list.get(i);
			to.setId(order.getId());
			Provider p = (Provider) providerDao.findById(order.getProvider().getId());
			to.setPro_name(p.getName());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			to.setTime(sdf.format(order.getTime()));
			Servicecatalog sc = (Servicecatalog) servicecatalogDao.findById(order.getServicecatalog().getId());
			Servicetype st = (Servicetype) servicetypeDao.findById(sc.getServicetype().getId());
			to.setSt_sc_name(st.getName() + "-" + sc.getName());
			to.setState("待评价");
			orderList.add(to);
		}
		return orderList;
	}

	/**
	 * 获得该用户已完成订单
	 * 
	 * @return 订单list
	 * @throws Exception
	 */
	public List getCompletedOrder() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		String re_account = request.getParameter("re_account");
		Resident r = (Resident) residentDao.findByAccount(re_account);
		int re_id = r.getId();
		List list = orderDao.getCompletedOrder(re_id);
		List orderList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			TotalOrder to = new TotalOrder();
			Order order = (Order) list.get(i);
			to.setId(order.getId());
			Provider p = (Provider) providerDao.findById(order.getProvider().getId());
			to.setPro_name(p.getName());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			to.setTime(sdf.format(order.getTime()));
			Servicecatalog sc = (Servicecatalog) servicecatalogDao.findById(order.getServicecatalog().getId());
			Servicetype st = (Servicetype) servicetypeDao.findById(sc.getServicetype().getId());
			to.setSt_sc_name(st.getName() + "-" + sc.getName());
			if (order.getState().equals(EnumOrder.ORDER_WAIT_REMARK)) {
				to.setState("待评价");
			} else {
				to.setState("已评价");
			}
			orderList.add(to);
		}
		return orderList;
	}

	/**
	 * 获得该用户所有订单
	 * 
	 * @return 订单list
	 * @throws Exception
	 */
	public List getAllOrders() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		String re_account = request.getParameter("re_account");
		Resident r = (Resident) residentDao.findByAccount(re_account);
		int re_id = r.getId();
		List list = orderDao.getAllOrders(re_id);
		List orderList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			TotalOrder to = new TotalOrder();
			Order order = (Order) list.get(i);
			to.setId(order.getId());
			Provider p = (Provider) providerDao.findById(order.getProvider().getId());
			to.setPro_name(p.getName());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			to.setTime(sdf.format(order.getTime()));
			Servicecatalog sc = (Servicecatalog) servicecatalogDao.findById(order.getServicecatalog().getId());
			Servicetype st = (Servicetype) servicetypeDao.findById(sc.getServicetype().getId());
			to.setSt_sc_name(st.getName() + "-" + sc.getName());
			if (order.getState().equals(EnumOrder.ORDER_WAIT_TAKE)) {
				to.setState("未接单");
			} else if (order.getState().equals(EnumOrder.ORDER_WAIT_COMFIRM)) {
				to.setState("待确认");
			} else if (order.getState().equals(EnumOrder.ORDER_WAIT_REMARK)) {
				to.setState("待评价");
			} else {
				to.setState("已评价");
			}
			orderList.add(to);
		}
		return orderList;
	}

	/**
	 * 获取订单详情
	 * 
	 * @return
	 * @throws Exception
	 */
	public List orderDetail() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		List list = new ArrayList();
		int order_id = Integer.parseInt(request.getParameter("order_id"));
		System.out.println(order_id);
		Order order = (Order) orderDao.getOrderById(order_id);
		OrderDetail2 od2 = new OrderDetail2();
		od2.setId(order_id);
		od2.setAddress(order.getAddress());
		od2.setMessage(order.getMessage());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		od2.setService_time(sdf.format(order.getService_time()));
		od2.setPlace_time(sdf.format(order.getTime()));
		od2.setPrice(order.getPrice());

		Resident resident = (Resident) residentDao.findById(order.getResident().getId());
		od2.setRe_name(resident.getRealname());
		od2.setRe_phone(resident.getPhone());
		Provider p = (Provider) providerDao.findById(order.getProvider().getId());
		od2.setPro_name(p.getName());
		Servicecatalog sc = (Servicecatalog) servicecatalogDao.findById(order.getServicecatalog().getId());
		Servicetype st = (Servicetype) servicetypeDao.findById(sc.getServicetype().getId());
		od2.setStsc_name(st.getName() + "-" + sc.getName());
		list.add(od2);
		return list;
	}

	/**
	 * 评价订单
	 * 
	 * @return 更新订单的结果
	 * @throws Exception
	 */
	public String remarkOrder() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		int order_id = Integer.parseInt(request.getParameter("order_id"));
		int rank = (int) Float.parseFloat(request.getParameter("rank"));
		String remark = request.getParameter("remark");
		Order order = (Order) orderDao.getOrderById(order_id);
		order.setRank(rank);
		order.setRemark(remark);
		order.setState(EnumOrder.ORDER_REMARKED);
		if (orderDao.update(order)) {
			return "succeed";
		} else {
			return "failed";
		}
	}

	// 供应商接单
	public Boolean acceptOrder(int order_id) {
		Order order = (Order) orderDao.getOrderById(order_id);
		order.setState(EnumOrder.ORDER_WAIT_COMFIRM);
		if (orderDao.update(order)) {
			CancelOrder cancelOrder = (CancelOrder) cancelorderDao.findByOrder_id(order_id);
			cancelorderDao.delete(cancelOrder);
			return true;
		} else
			return false;
	}

	// 供应商拒绝订单
	public Boolean rejectOrder(int order_id) {
		Order order = (Order) orderDao.getOrderById(order_id);
		order.setState(EnumOrder.ORDER_CANCELED);
		if (orderDao.update(order)) {
			CancelOrder cancelOrder = (CancelOrder) cancelorderDao.findByOrder_id(order_id);
			cancelorderDao.delete(cancelOrder);
			return true;
		} else
			return false;
	}

	/**
	 * 确认订单
	 */
	public String confirmOrder() throws Exception {
		request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		int order_id = Integer.parseInt(request.getParameter("order_id"));
		Order order = (Order) orderDao.getOrderById(order_id);
		order.setState(EnumOrder.ORDER_WAIT_REMARK);
		if (orderDao.update(order)) {
			return "succeed";
		} else {
			return "failed";
		}
	}

	/**
	 * 超过24小时自动取消订单
	 */
	public void autoCancel() {
		CancelOrder cancelOrder = (CancelOrder) cancelorderDao.getLong();
		System.out.println(cancelOrder.getId());
		Date date = new Date();
		Date date2 = cancelOrder.getPlacetime();
		System.out.println(date.getTime() - date2.getTime());
		// if((date.getTime()-date2.getTime())/(1000*60)>=1440){//如果时间差大于等于24小时
		if ((date.getTime() - date2.getTime()) / (1000 * 60) >= 1) {
			Order order = (Order) orderDao.getOrderById(cancelOrder.getOrder_id());
			order.setState(EnumOrder.ORDER_CANCELED);
			orderDao.update(order);
			System.out.println("正在取消订单" + cancelOrder.getOrder_id());
			cancelorderDao.delete(cancelOrder);
		}
	}
}
